package javax.clear.sun.reflect.misc;

import java.lang.reflect.Modifier;

public final class ReflectUtil
{

    private ReflectUtil()
    {
    }

    public static Class forName(String s)
        throws ClassNotFoundException
    {
        checkPackageAccess(s);
        return Class.forName(s);
    }

    public static Object newInstance(Class class1)
        throws InstantiationException, IllegalAccessException
    {
        checkPackageAccess(class1);
        return class1.newInstance();
    }

    public static void ensureMemberAccess(Class class1, Class class2, Object obj, int i)
        throws IllegalAccessException
    {
        if(obj == null && Modifier.isProtected(i))
        {
            int j = i;
            j &= -5;
            j |= 1;
            Reflection.ensureMemberAccess(class1, class2, obj, j);
            try
            {
                j &= -2;
                Reflection.ensureMemberAccess(class1, class2, obj, j);
                return;
            }
            catch(IllegalAccessException illegalaccessexception)
            {
                if(isSubclassOf(class1, class2))
                    return;
                else
                    throw illegalaccessexception;
            }
        } else
        {
            Reflection.ensureMemberAccess(class1, class2, obj, i);
            return;
        }
    }

    private static boolean isSubclassOf(Class class1, Class class2)
    {
        for(; class1 != null; class1 = class1.getSuperclass())
            if(class1 == class2)
                return true;

        return false;
    }

    public static void checkPackageAccess(Class class1)
    {
        checkPackageAccess(class1.getName());
    }

    public static void checkPackageAccess(String s)
    {
        SecurityManager securitymanager = System.getSecurityManager();
        if(securitymanager != null)
        {
            String s1 = s.replace('/', '.');
            if(s1.startsWith("["))
            {
                int i = s1.lastIndexOf('[') + 2;
                if(i > 1 && i < s1.length())
                    s1 = s1.substring(i);
            }
            int j = s1.lastIndexOf('.');
            if(j != -1)
                securitymanager.checkPackageAccess(s1.substring(0, j));
        }
    }

    public static boolean isPackageAccessible(Class class1)
    {
        try
        {
            checkPackageAccess(class1);
        }
        catch(SecurityException securityexception)
        {
            return false;
        }
        return true;
    }
}